Imports System
Imports System.Configuration
Imports MyClasses
Imports DAL
Imports BAL
Imports C1.Win.C1FlexGrid
Imports System.Text
Imports System.Drawing.Printing

Public Class frmSaleFinal

#Region "Declaration"

    Public intCustID As Integer
    Public isBillSaved As Byte
    Private intTotalColumns As Integer = 9      'SALE ITEM'S NO OF COLUMNS       
    Private intGrdCntRows As Integer = 20
    Private intBills As Integer
    Private BtLoading As Byte                 'VARIABLE IS USED TO AVOID UNNECESSARY LOOPS/EVENTS/EXECUTION WHILE SETTING OR LOADING THE DATA                         

    Dim tableFont, titlefont, headfont, tabletitlefont As Font
    Dim X1, X2, X3 As Integer
    Dim wi As Integer
    Dim PHi As Double
    Dim Y As Integer
    Dim intPrintNext As Integer = 1
    Dim pageWidth As Integer
    Dim dobTotal As Double

    Dim curY As Integer
    Dim Foot1 As String
    Dim Foot2 As String
    Dim Foot3 As String
    Dim PageNo As Integer = 1 'FOR SHOWING PAGE NO IN BILL
    '---------------------------------SOMETHING EXTRA --------------------------------------------------------'
    '
    'Byte DataType used as boolean   : 1 --TRUE
    '                                : 0 --FALSE  
    '
    '---------------------------------FORM SHORTCUTS --------------------------------------------------------'

#End Region '"DECLARATION"
    '---------------------------------     CODE    --------------------------------------------------------'

#Region " Form( & control) Events"

#Region "READ ONLY TEXT BOXES"



    'Private Sub txtDiscount_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDiscount.KeyDown
    '    Try
    '        If e.Alt Then Exit Sub
    '        If e.KeyCode = Keys.Enter Then txtPaidAmt.Focus()
    '        If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
    '            e.SuppressKeyPress = True
    '        ElseIf e.Shift = True Then
    '            e.SuppressKeyPress = True
    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, " txtDiscount_KeyDown")
    '    End Try
    'End Sub

    'Private Sub txtPaid_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPaidAmt.KeyDown
    '    If e.Alt Then Exit Sub
    '    Try
    '        If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
    '            e.SuppressKeyPress = True
    '        ElseIf e.Shift = True Then
    '            e.SuppressKeyPress = True
    '        ElseIf e.KeyCode = Keys.Enter Then
    '            btnOkPrint.Focus()
    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtPaid_KeyDown")
    '    End Try
    'End Sub

    'Private Sub txtPaid_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPaidAmt.LostFocus
    '    Try
    '        If Trim(Me.txtPaidAmt.Text) = "" Then Me.txtPaidAmt.Text = "0.00"
    '        Call CalculateReturnAmt()
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtPaid_LostFocus")
    '    End Try
    'End Sub

    'Private Sub txtCredit_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCredit.LostFocus
    '    Try
    '        Call CalculateReturnAmt()
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtCredit_LostFocus")
    '    End Try
    'End Sub

    'Private Sub txtDisPercent_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDisPercent.KeyDown
    '    Try
    '        If e.Alt Then Exit Sub
    '        If e.KeyCode = Keys.Enter Then txtPaidAmt.Focus()
    '        If BCommon.ValidateText(e.KeyCode, "NUM", False) = False Then
    '            e.SuppressKeyPress = True
    '        ElseIf e.Shift = True Then
    '            e.SuppressKeyPress = True
    '        End If
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, " txtDiscount_KeyDown")
    '    End Try
    'End Sub

    'Private Sub txtDisPercent_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDisPercent.LostFocus
    '    Try
    '        Call UpdateDiscountValues("P")
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtDisPercent_LostFocus")
    '    End Try
    'End Sub

    'Private Sub txtDiscount_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDiscount.LostFocus
    '    Try
    '        Call UpdateDiscountValues("A")
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "txtDiscount_LostFocus")
    '    End Try
    'End Sub

#End Region

    Private Sub btnOkPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOkPrint.Click
        Try
            If intCustID <> 0 Then
                If ValidateData() Then SaveData(intCustID)
            ElseIf ValidateData() Then
                SaveData(cmDCustomerName.SelectedValue)
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnOkPrint_Click")
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Try
            Me.Close()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnClose_Click")
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Try
            If intCustID <> 0 Then
                Me.Close()
                Exit Sub
            End If
            Call ClearData()

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "btnCancel_Click")
        End Try
    End Sub

    Private Sub frmSaleFinal_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Me.MdiParent = Nothing
    End Sub

    Private Sub frmSalePrint_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
        Try
            If e.Control = True Then
                If e.Alt = False Then
                    Select Case e.KeyCode
                        Case Keys.S         'SAVE SELECTED ITEMS
                            Call SaveData(0)
                    End Select
                End If
            ElseIf e.KeyCode = Keys.F1 Then
                e.SuppressKeyPress = True
                'Help.ShowHelp(Me, "Pharma.chm", HelpNavigator.KeywordIndex, "Regular Sale")
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "frmSalePrint_KeyUp")
        Finally

        End Try
    End Sub

    Private Sub frmSaleFinal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            BCommon.SetFormStandards(Me)
            Call DisplayData()
            BtLoading = 1
            'If intCustID = 0 Then Me.WindowState = FormWindowState.Maximized
            Dim strCurrancy As String = ConfigurationManager.AppSettings("Currency").ToString()
            Me.lblRs1.Text = strCurrancy
            Me.lblRs2.Text = strCurrancy
            Me.lblRs3.Text = strCurrancy
            Me.lblRs4.Text = strCurrancy
            Me.lblRs5.Text = strCurrancy
            BCommon.SetTextReadOnly(txtVoucher)
            BCommon.SetTextReadOnly(txtDiscount)
            BCommon.SetTextReadOnly(txtDisPercent)
            BCommon.SetTextReadOnly(txtTotal)
            BCommon.SetTextReadOnly(txtNetAmount)
            BCommon.SetTextReadOnly(txtBalance)
            BCommon.SetTextReadOnly(txtPaidAmt)
            BtLoading = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "frmSaleFinal_Load")
        End Try
    End Sub

    Private Sub cmDCustomerName_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmDCustomerName.KeyDown
        Try
            If Not e.Alt AndAlso e.KeyCode = Keys.Enter Then cmDDoctor.Focus()
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDCustomerName_KeyDown")
        End Try
    End Sub

    Private Sub cmDCustomerName_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmDCustomerName.SelectedValueChanged
        If BtLoading = 1 Then Exit Sub
        Try

            If Not IsNothing(cmDCustomerName.SelectedValue) AndAlso cmDCustomerName.SelectedValue > 0 Then
                Call SetCustomerBills()
            Else
                ClearData()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDCustomerName_SelectedValueChanged")
        End Try
    End Sub

    Private Sub cmDDoctor_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmDDoctor.KeyDown
        Try
            If e.Alt Then Exit Sub
            If e.KeyCode = Keys.Enter Then
                fgItems.Focus()
                fgItems.Col = 1
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmDDoctor_KeyDown")
        End Try
    End Sub

    Private Sub cmbTitle_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbTitle.KeyDown
        Try
            If e.Alt Then
                Exit Sub
            ElseIf e.KeyCode = Keys.Enter Then
                cmDCustomerName.Focus()
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "cmbTitle_KeyDown")
        End Try
    End Sub

    Private Sub StripTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StripTimer.Tick
        Try
            lblStrip.Left -= 4
            If lblStrip.Left + lblStrip.Width < 0 Then
                lblStrip.Left = Me.Width
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "StripTimer_Tick")
        End Try
    End Sub
#End Region

#Region "GRID SETTINGS"

    Private Sub SetGrids()
        Try
            'ITEM DISPLAY GRID
            With fgItems
                .Left = grpheader.Left
                .Width = grpheader.Width
                .AllowDelete = False
                .Rows.Count = intGrdCntRows
                .Cols.Fixed = 0

                .ScrollBars = ScrollBars.None
                .AllowAddNew = False
                .SelectionMode = SelectionModeEnum.RowRange

                Call SetGridCaptions()

                'NON EDITABLE COLUMNS 
                .AllowEditing = False


                'NUMBERS ONLY COLUMN
                .Cols("QTY").DataType = System.Type.GetType("System.Int32")
                .Cols("RATE").DataType = System.Type.GetType("System.Double")
                .Cols("AMOUNT").DataType = System.Type.GetType("System.Decimal")
                .Cols("RATE").Format = "0.00"
                .Cols("AMOUNT").Format = "0.00"

                'DATE COLUMN
                .Cols("EXP").DataType = System.Type.GetType("System.DateTime")
                .Cols("EXP").Format = "MMM/yy"

                'COLOR SETTINGS 
                .Styles.Normal.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
                .Styles.Alternate.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised

                'COLUMN'S TEXT ALIGNMENT
                .Cols("CODE").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.CenterCenter
                .Cols("ITEMNAME").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.LeftCenter
                .Cols("CLRcode").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.LeftCenter
                .Cols("RATE").TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.RightCenter

                .ScrollBars = ScrollBars.None
            End With
            With FgCustBills

                .Rows.Count = 10
                .SelectionMode = SelectionModeEnum.Row

                'AMOUNT COLUMN
                .Cols("AMOUNT").DataType = System.Type.GetType("System.Decimal")
                .Cols("DISCOUNTG").DataType = System.Type.GetType("System.Decimal")
                .Cols("PAIDAMOUNT").DataType = System.Type.GetType("System.Decimal")
                .Cols("BALANCE").DataType = System.Type.GetType("System.Decimal")
                .Cols("PAYMENT").DataType = System.Type.GetType("System.Decimal")
                .Cols("DISCOUNT").DataType = System.Type.GetType("System.Decimal")
                .Cols("SALEDATE").DataType = System.Type.GetType("System.DateTime")

                .Cols("AMOUNT").Format = "0.00"
                .Cols("DISCOUNTG").Format = "0.00"
                .Cols("PAIDAMOUNT").Format = "0.00"
                .Cols("BALANCE").Format = "0.00"
                .Cols("PAYMENT").Format = "0.00"
                .Cols("DISCOUNT").Format = "0.00"
                .Cols("SALEDATE").Format = "dd/MM/yy"

                'COLOR SETTINGS 
                .Styles.Normal.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised
                .Styles.Alternate.TextEffect = C1.Win.C1FlexGrid.TextEffectEnum.Raised

                'HIDDEN COLUMNS 
                .Cols("SALEID").Visible = False
                .Cols("ITEMS").Visible = False

                'NON EDITABLE COLUMNS
                .Cols("SALEID").AllowEditing = False
                .Cols("VOUCHERNO").AllowEditing = False
                .Cols("SALEDATE").AllowEditing = False
                .Cols("AMOUNT").AllowEditing = False
                .Cols("PAIDAMOUNT").AllowEditing = False
                .Cols("BALANCE").AllowEditing = False
                .Cols("PAYMENT").AllowEditing = False
                .Cols("DISCOUNTG").AllowEditing = False

                ' EDITABLE COLUMNS
                .Cols("DISCOUNT").AllowEditing = True
                .ScrollBars = ScrollBars.None

                'TEXT ALLIGNMENT
                .Cols("AMOUNT").TextAlign = TextAlignEnum.RightCenter
                .Cols("DISCOUNTG").TextAlign = TextAlignEnum.RightCenter
                .Cols("PAIDAMOUNT").TextAlign = TextAlignEnum.RightCenter
                .Cols("BALANCE").TextAlign = TextAlignEnum.RightCenter
                .Cols("PAYMENT").TextAlign = TextAlignEnum.RightCenter
                .Cols("DISCOUNT").TextAlign = TextAlignEnum.RightCenter

            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetGrids")
        End Try
    End Sub

    Private Sub SetColumnWidths()
        Dim intGridWidth As Integer

        Try
            With fgItems
                intGridWidth = .Width - 5
                .Cols("CODE").Width = intGridWidth / 11
                .Cols("ITEMNAME").Width = intGridWidth / 10 * 3
                .Cols("COMPANY").Width = intGridWidth / 11
                .Cols("SCHEME").Width = intGridWidth / 11
                .Cols("CLRcode").Width = intGridWidth / 11
                .Cols("QTY").Width = intGridWidth / 12
                .Cols("RATE").Width = intGridWidth / 11
                .Cols("AMOUNT").Width = intGridWidth / 12
                .ExtendLastCol = True                        'EXTENDS LAST COLUMN UPTO REMAINED COLUMN WIDTH 
            End With
            With FgCustBills
                intGridWidth = .Width - 5
                .Cols("SALEID").Width = 0                    'HIDDEN COLUMN  
                .Cols("VOUCHERNO").Width = intGridWidth / 8
                .Cols("SALEDATE").Width = intGridWidth / 8
                .Cols("AMOUNT").Width = intGridWidth / 8
                .Cols("DISCOUNTG").Width = intGridWidth / 8
                .Cols("PAIDAMOUNT").Width = intGridWidth / 8
                .Cols("BALANCE").Width = intGridWidth / 8
                .Cols("DISCOUNT").Width = intGridWidth / 8
                .Cols("PAYMENT").Width = intGridWidth / 8
                .Cols("ITEMS").Width = 0                     'HIDDEN COLUMN
                .ExtendLastCol = True                        'EXTENDS LAST COLUMN UPTO REMAINED COLUMN WIDTH 
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetColumnWidths")
        End Try
    End Sub

    Private Sub SetGridCaptions()
        Try
            With fgItems
                'SET COLUMN NAMES
                .Cols.Count = intTotalColumns
                .Cols(0).Name = "CODE"
                .Cols(1).Name = "ITEMNAME"
                .Cols(2).Name = "COMPANY"
                .Cols(3).Name = "CLRcode"
                .Cols(4).Name = "EXP"
                .Cols(5).Name = "SCHEME"
                .Cols(6).Name = "QTY"
                .Cols(7).Name = "RATE"
                .Cols(8).Name = "AMOUNT"

                'SET COLUMN CAPTIONS
                .Cols("CODE").Caption = "Code"
                .Cols("ITEMNAME").Caption = "ItemName"
                .Cols("COMPANY").Caption = "Company"
                .Cols("CLRcode").Caption = "Batch No."
                .Cols("EXP").Caption = "EXP"
                .Cols("SCHEME").Caption = "Scheme"
                .Cols("QTY").Caption = "Qty"
                .Cols("RATE").Caption = "Price"
                .Cols("AMOUNT").Caption = "Amount"

            End With

            With FgCustBills
                .Cols.Count = 10
                'SET COLUMN NAMES
                .Cols(0).Name = "SALEID"
                .Cols(1).Name = "VOUCHERNO"
                .Cols(2).Name = "SALEDATE"
                .Cols(3).Name = "DISCOUNTG"
                .Cols(4).Name = "AMOUNT"
                .Cols(5).Name = "PAIDAMOUNT"
                .Cols(6).Name = "BALANCE"
                .Cols(7).Name = "DISCOUNT"
                .Cols(8).Name = "PAYMENT"
                .Cols(9).Name = "ITEMS"

                'SET COLUMN CAPTIONS
                .Cols("SALEID").Caption = "SaleID"
                .Cols("VOUCHERNO").Caption = "Voucher No"
                .Cols("SALEDATE").Caption = "SaleDate"
                .Cols("DISCOUNTG").Caption = "Prev Discount"
                .Cols("AMOUNT").Caption = "Amount"
                .Cols("PAIDAMOUNT").Caption = "Paid Amount"
                .Cols("BALANCE").Caption = "Balance"
                .Cols("DISCOUNT").Caption = "Discount"
                .Cols("PAYMENT").Caption = "Payment"
                .Cols("ITEMS").Caption = "Items"
            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetGridCaption")
        End Try
    End Sub

#End Region '"GRID SETTINGS"

#Region "GRID EVENT FUNCTIONS"

    Private Sub FgCustBills_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FgCustBills.Click
        Try
            With FgCustBills
                If IsNothing(.Item(.Row, "ITEMS")) OrElse Trim(.Item(.Row, "ITEMS")) = "" Then Exit Sub
                Dim strRows() As String = .Item(.Row, "ITEMS").ToString().Split("-")
                fgItems.Select(CInt(strRows(0)), 0, CInt(strRows(1)), fgItems.Cols.Count - 1, True)
                fgItems.TopRow = CInt(strRows(0))
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetGridCaption")
        End Try
    End Sub

    Private Sub FgCustBills_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles FgCustBills.KeyDown
        Try
            With FgCustBills
                If e.KeyCode = Keys.Enter Then
                    If IsNothing(.Item(.Row, "ITEMS")) OrElse Trim(.Item(.Row, "ITEMS")) = "" Then Exit Sub
                    Dim strRows() As String = .Item(.Row, "ITEMS").ToString().Split("-")
                    fgItems.Select(CInt(strRows(0)), 0, CInt(strRows(1)), fgItems.Cols.Count - 1, True)
                    fgItems.TopRow = CInt(strRows(0))
                End If
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "FgCustBills_KeyDown")
        End Try
    End Sub

    Private Sub FgCustBills_ValidateEdit(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.ValidateEditEventArgs) Handles FgCustBills.ValidateEdit
        Try
            With FgCustBills
                If Trim(.Editor.Text) = "" Then .Editor.Text = 0
                If CDbl(.Editor.Text) >= CDbl(.Item(e.Row, "BALANCE")) Then
                    .Item(e.Row, "DISCOUNT") = 0 '.Item(e.Row, "BALANCE")
                    .Editor.Text = 0 '.Item(e.Row, "BALANCE")
                Else
                    .Item(e.Row, "DISCOUNT") = .Editor.Text
                End If
                Dim DiscTotal As Double
                Dim dblPay As Double
                For intCount As Integer = 1 To .Rows.Count - 2
                    If IsNothing(.Item(intCount, "DISCOUNT")) OrElse Trim(.Item(intCount, "DISCOUNT")) = "" Then Exit For
                    .Item(intCount, "PAYMENT") = .Item(intCount, "BALANCE") - .Item(intCount, "DISCOUNT")
                    DiscTotal += CDbl(.Item(intCount, "DISCOUNT"))
                    dblPay += CDbl(.Item(intCount, "PAYMENT"))
                Next
                .Item(.Rows.Count - 1, "DISCOUNT") = BCommon.FormatAmount(DiscTotal)
                .Item(.Rows.Count - 1, "PAYMENT") = BCommon.FormatAmount(dblPay)
                Call SetFinalAmounts()
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "FgCustBills_ValidateEdit")
        End Try
    End Sub

    Private Sub FgCustBills_BeforeEdit(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.RowColEventArgs) Handles FgCustBills.BeforeEdit
        If IsNothing(FgCustBills.Item(e.Row, 0)) OrElse Trim(FgCustBills.Item(e.Row, 0)) = "" Then e.Cancel = True
    End Sub

#End Region '"GRID EVENT FUNCTIONS"

#Region "USER DEFINED FUNCITONS"

    Private Sub SetFinalAmounts()
        Try
            With FgCustBills
                txtTotal.Text = .Item(.Rows.Count - 1, "AMOUNT")
                txtDiscount.Text = .Item(.Rows.Count - 1, "DISCOUNTG") + .Item(.Rows.Count - 1, "DISCOUNT")
                txtBalance.Text = .Item(.Rows.Count - 1, "PAIDAMOUNT")  'Previous Payments Done
                txtPaidAmt.Text = .Item(.Rows.Count - 1, "PAYMENT")     'Current Payment 
                txtDisPercent.Text = BCALC.GetDiscount(txtTotal.Text, txtDiscount.Text, "A")
                txtNetAmount.Text = BCommon.FormatAmount(CDbl(txtTotal.Text) - CDbl(txtDiscount.Text) - .Item(.Rows.Count - 1, "PAIDAMOUNT"))

            End With

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetFinalAmounts")
        End Try

    End Sub

    Private Sub ClearCustomerBills()
        Try
            BtLoading = 1
            With FgCustBills
                If .Rows.Count > 1 Then
                    .Clear(C1.Win.C1FlexGrid.ClearFlags.Content, 1, 0, .Rows.Count - 1, .Cols.Count - 1)
                    .Rows.RemoveRange(1, .Rows.Count - 1)
                    .Rows.Count = 10
                    .Refresh()
                End If
            End With
            With fgItems
                If .Rows.Count > 1 Then
                    .Clear(C1.Win.C1FlexGrid.ClearFlags.Content, 1, 0, .Rows.Count - 1, .Cols.Count - 1)
                    .Rows.RemoveRange(1, .Rows.Count - 1)
                    .Rows.Count = intGrdCntRows
                    .Refresh()
                End If
            End With
            txtBalance.Text = "0.00"
            txtNetAmount.Text = "0.00"
            txtPaidAmt.Text = "0.00"
            txtTotal.Text = "0.00"
            txtDiscount.Text = "0.00"
            txtDisPercent.Text = "0.00"
            BtLoading = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearCustomerBills")
        End Try
    End Sub

    Private Sub SetCustomerBills()
        Try
            Dim dtCustRecord As DataTable = DSalePrint.GetCustomerPrintBills(cmDCustomerName.SelectedValue.ToString())

            Dim intCurrentRow As Integer = 1

            Dim dblTotal As Double
            Dim dblDisc As Double
            Dim dblBalance As Double
            Dim dblPaid As Double
            Dim intStartRow As Integer
            With FgCustBills
                Call ClearCustomerBills()
                If dtCustRecord.Rows.Count <= 0 Then
                    BCommon.ShowMsgError(10345)
                    cmDCustomerName.SelectedValue = 0
                    '.Rows.Count = 10
                    Exit Sub
                End If
                intBills = dtCustRecord.Rows.Count
                If .Rows.Count <= dtCustRecord.Rows.Count Then .Rows.Count = dtCustRecord.Rows.Count + 2
                Dim dtBillItems As DataTable

                For intRowCount As Integer = 0 To dtCustRecord.Rows.Count - 1

                    .Item(intRowCount + 1, "SALEID") = dtCustRecord.Rows(intRowCount).Item(0)
                    .Item(intRowCount + 1, "VOUCHERNO") = dtCustRecord.Rows(intRowCount).Item(1)
                    .Item(intRowCount + 1, "SALEDATE") = dtCustRecord.Rows(intRowCount).Item(2)

                    .Item(intRowCount + 1, "AMOUNT") = IIf(IsDBNull(dtCustRecord.Rows(intRowCount).Item(3)), 0, dtCustRecord.Rows(intRowCount).Item(3))
                    dblTotal += .Item(intRowCount + 1, "AMOUNT")

                    .Item(intRowCount + 1, "DISCOUNTG") = IIf(IsDBNull(dtCustRecord.Rows(intRowCount).Item(4)), 0, dtCustRecord.Rows(intRowCount).Item(4))
                    dblDisc += .Item(intRowCount + 1, "DISCOUNTG")

                    .Item(intRowCount + 1, "PAIDAMOUNT") = IIf(IsDBNull(dtCustRecord.Rows(intRowCount).Item(5)), 0, dtCustRecord.Rows(intRowCount).Item(5))
                    dblPaid += .Item(intRowCount + 1, "PAIDAMOUNT")

                    .Item(intRowCount + 1, "BALANCE") = IIf(IsDBNull(dtCustRecord.Rows(intRowCount).Item(6)), 0, dtCustRecord.Rows(intRowCount).Item(6))
                    dblBalance += .Item(intRowCount + 1, "BALANCE")

                    .Item(intRowCount + 1, "PAYMENT") = .Item(intRowCount + 1, "BALANCE")
                    .Item(intRowCount + 1, "DISCOUNT") = 0
                    dtBillItems = DSalePrint.GetBillItems(dtCustRecord.Rows(intRowCount).Item(0))

                    With fgItems
                        If intCurrentRow + dtBillItems.Rows.Count >= .Rows.Count Then .Rows.Count += dtBillItems.Rows.Count
                        intStartRow = intCurrentRow
                        For intItemCount As Integer = 0 To dtBillItems.Rows.Count - 1
                            .Item(intCurrentRow, "CODE") = dtBillItems.Rows(intItemCount).Item(0)
                            .Item(intCurrentRow, "ITEMNAME") = dtBillItems.Rows(intItemCount).Item(1)
                            .Item(intCurrentRow, "COMPANY") = dtBillItems.Rows(intItemCount).Item(2)
                            .Item(intCurrentRow, "CLRcode") = dtBillItems.Rows(intItemCount).Item(3)
                            .Item(intCurrentRow, "EXP") = dtBillItems.Rows(intItemCount).Item(4)

                            'dtBillItems.Rows.Item(4)'SCHEEM ID
                            If dtBillItems.Rows(intItemCount).Item(6) > 0 Then 'SCHEEM ITEM QUANTITY
                                .Item(intCurrentRow, "SCHEME") = dtBillItems.Rows(intItemCount).Item(6)
                            ElseIf dtBillItems.Rows(intItemCount).Item(5) > 0 Then 'SCHEEM ID
                                .Item(intCurrentRow, "SCHEME") = BScheme.GetSchemeName(BScheme.GetScheme(dtBillItems.Rows(intItemCount).Item(5)))
                            Else
                                .Item(intCurrentRow, "SCHEME") = ""
                            End If
                            .Item(intCurrentRow, "QTY") = dtBillItems.Rows(intItemCount).Item(7)
                            .Item(intCurrentRow, "RATE") = dtBillItems.Rows(intItemCount).Item(8)
                            .Item(intCurrentRow, "AMOUNT") = dtBillItems.Rows(intItemCount).Item(9)
                            SetRowColor(intCurrentRow, intRowCount + 1)
                            intCurrentRow += 1
                        Next
                    End With
                    .Item(intRowCount + 1, "ITEMS") = intStartRow.ToString() & "-" & (intCurrentRow - 1).ToString()
                Next

                'SET TOTAL 
                .Rows(.Rows.Count - 1).Style = .Styles.Frozen
                .Item(.Rows.Count - 1, "VOUCHERNO") = "Total(Rs)"
                .Item(.Rows.Count - 1, "DISCOUNTG") = BCommon.FormatAmount(dblDisc)
                .Item(.Rows.Count - 1, "AMOUNT") = BCommon.FormatAmount(dblTotal)  'Amont Is Amount + Total Taxes (Its not Gross Amount)
                .Item(.Rows.Count - 1, "PAIDAMOUNT") = BCommon.FormatAmount(dblPaid)
                .Item(.Rows.Count - 1, "BALANCE") = BCommon.FormatAmount(dblBalance)
                .Item(.Rows.Count - 1, "PAYMENT") = .Item(.Rows.Count - 1, "BALANCE")
                .Item(.Rows.Count - 1, "DISCOUNT") = "0.00"
                Call SetFinalAmounts()
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetCustomerBills")
        End Try
    End Sub

    Private Sub SetRowColor(ByVal RowNo As Integer, ByVal RowColor As Integer)
        Dim FreezeStyle As C1.Win.C1FlexGrid.CellStyle
        Try
            FreezeStyle = fgItems.Rows(RowNo).StyleNew
            FreezeStyle.BackColor = GetRowColor(RowColor)
            fgItems.Rows(RowNo).Style = FreezeStyle
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetRowColor")
        Finally
            FreezeStyle = Nothing
        End Try
    End Sub

    Private Function GetRowColor(ByVal RowNo As Integer) As Color
        Try
            If RowNo Mod 2 = 0 Then
                Return CConstants.NormalRowColor
            Else
                Return CConstants.AlternateRowColor
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "GetRowColor")
            Return Nothing
        End Try
    End Function

    'Private Sub UpdateDiscountValues(ByVal AmtOrPerc As Char)
    '    Try
    '        If Trim(Me.txtDiscount.Text) = "" Then Me.txtDiscount.Text = "0.00"
    '        If Trim(Me.txtDisPercent.Text) = "" Then Me.txtDisPercent.Text = "0.00"

    '        If AmtOrPerc = "A" Then                'Amount
    '            If Convert.ToDouble(Me.txtDiscount.Text) > Convert.ToDouble(Me.txtTotal.Text) Then
    '                MessageBox.Show("Discount Amount Should be Less than or Equal Total Amount", "Pharmacy Message")
    '                Me.txtDiscount.Focus()
    '                Exit Sub
    '            End If
    '            Me.txtDisPercent.Text = BCALC.GetDiscount(txtTotal.Text, Me.txtDiscount.Text, "A")
    '        Else 'Percentage
    '            If CDbl(Me.txtDisPercent.Text) > 100 Then
    '                BCommon.ShowMsgError(10346)
    '                txtDisPercent.Focus()
    '                Exit Sub
    '            End If
    '            Me.txtDiscount.Text = BCALC.GetDiscount(txtTotal.Text, Me.txtDisPercent.Text, "P")
    '        End If
    '        Me.txtNetAmount.Text = Format(Convert.ToDouble(Me.txtTotal.Text) - Convert.ToDouble(Me.txtDiscount.Text), "0.00")
    '        Call CalculateReturnAmt()
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "UpdateDiscountValues")
    '    End Try
    'End Sub

    'Private Sub ClearGridData()
    '    Try
    '        BtLoading = 1
    '        Me.fgItems.Rows.RemoveRange(1, Me.fgItems.Rows.Count - 1)
    '        Me.fgItems.Rows.Count = intGrdCntRows
    '        Me.txtBalance.Text = "0.00"
    '        Me.txtNetAmount.Text = "0.00"
    '        Me.txtDiscount.Text = "0.00"
    '        Me.txtTotal.Text = "0.00"
    '        Me.txtPaidAmt.Text = "0.00"
    '        BtLoading = 0
    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearGridData")
    '    End Try
    'End Sub

    Private Sub DisplayData()
        Try
            ClearData()
            BtLoading = 1


            'BCommon.SetComboValues(cmDDoctor, DDoctor.GetDoctorList(), "DoctorID", "Name")
            BCommon.SetComboValues(cmDCustomerName, DCustomer.GetCustomerName(False), "CustID", "Name")
            BCommon.SetComboValues(cmbTitle, "TITLE", False)

            Call SetGrids()
            Call SetColumnWidths()
            Dim dtCity As DataTable = DAddress.GetCity()
            dtCity.PrimaryKey = New DataColumn() {dtCity.Columns("CityCD")}
            Dim RowCity As DataRow = dtCity.Rows.Find(BCommon.GetConfigValues("City"))
            txtAddress.Text = RowCity("Description").ToString

            'FROM FRMSALE-DISPLAYDATA
            dtpSaleDate.Value = Now.Date
            'To Set Customer Combo blank Value at the time of Form Load
            cmDCustomerName.SelectedIndex = -1

            If intCustID <> 0 Then
                cmDCustomerName.SelectedValue = intCustID
                cmDCustomerName.Enabled = False
                Call SetCustomerBills()
            End If
            ' Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
            BtLoading = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DisplayData")
        End Try
    End Sub

    Private Sub ClearData()
        Try
            txtVoucher.Text = BCommon.GetSequentialID("SALEBILL")
            Call ClearCustomerBills()
            dobTotal = 0.0
            BtLoading = 1
            cmDCustomerName.SelectedValue = 0
            cmDDoctor.SelectedValue = 0
            txtAddress.Text = ""
            BtLoading = 0
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ClearData")
        End Try
    End Sub

    Private Function SaveData(ByVal CustID As Integer) As Byte
        Dim objsale As CSale
        Dim intResult As Integer
        Dim strBills As New StringBuilder
        Try
            objsale = SetSaleData(CustID)
            Dim Bills(intBills - 1) As CSaleBills
            With FgCustBills
                For intCount As Integer = 0 To intBills - 1
                    Bills(intCount) = New CSaleBills
                    Bills(intCount).SaleBillID = .Item(intCount + 1, "SALEID")
                    Bills(intCount).Amount = .Item(intCount + 1, "AMOUNT")
                    Bills(intCount).NewDiscount = .Item(intCount + 1, "DISCOUNT")
                    Bills(intCount).PaidAmt = .Item(intCount + 1, "PAYMENT")
                    strBills.Append(Bills(intCount).SaleBillID.ToString() & ",")
                Next
            End With
            If strBills.Length > 0 Then strBills.Remove(strBills.Length - 1, 1)
            objsale.SaleBills = strBills.ToString()
            intResult = DSale.SaveFinalBill(objsale, Bills)
            If intResult > 0 Then
                'If MessageBox.Show(BCommon.GetMessage(10321), BCommon.GetConfigValues("MsgTitle"), MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                If BCommon.ShowMsgError(10321, "YN") = Windows.Forms.DialogResult.Yes Then
                    Call PrintFinalBill()
                End If
                If intCustID <> 0 Then
                    Me.Close()
                Else
                    ClearData()
                End If
            Else
                BCommon.ShowMsgError(4)
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SaveData")
            Return 0
        End Try
    End Function

    Private Function SetSaleData(ByVal CustID As Integer) As CSale
        Dim objsale As New CSale

        Try
            With objsale
                .PartyID = CustID
                .PromoterID = 0
                .SaleDate = Me.dtpSaleDate.Value
                .IsFinalBill = True
                .Amount = txtTotal.Text
                .Discount = BCommon.BlankToDecimal(txtDiscount.Text)
                .PaidAmt = BCommon.BlankToDecimal(txtPaidAmt.Text)
                .TotalTax = BCommon.BlankToDecimal(txtTax.Text)
                .DebitAmt = BCommon.BlankToDecimal(txtDebit.Text)
                .CreditAmt = BCommon.BlankToDecimal(txtCredit.Text)
                .GrossAmt = txtNetAmount.Text
                .SaleType = "CS" 'CURRENTLY FINAL BILL IS AGAINST ALL PAYMENT MEANS ALL PAYMENTS ARE DONE SO BY DEFAULT CASH IS SELECTED.
                'If Convert.ToDouble(Me.txtNetAmount.Text) > Convert.ToDouble(Me.txtPaidAmt.Text) Then
                '    .SaleType = "CS"
                'ElseIf Convert.ToDouble(Me.txtNetAmount.Text) = Convert.ToDouble(Me.txtPaidAmt.Text) Then
                '    .SaleType = "CR"
                'End If
                .DrID = cmDDoctor.SelectedValue
            End With
            Return objsale
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetSaleData")
            Return Nothing
        End Try
    End Function

    Private Function ValidateData() As Boolean
        Try
            If DateTime.Compare(Me.dtpSaleDate.Value, DateTime.Now()) > 0 Then
                BCommon.ShowMsgError(10228)
                dtpSaleDate.Value = DateTime.Now()
                dtpSaleDate.Focus()
                Return False
            ElseIf IsNothing(cmDCustomerName.SelectedValue) OrElse cmDCustomerName.SelectedValue <= 0 Then
                BCommon.ShowMsgError(10309)
                cmDCustomerName.Focus()
                Return False
            ElseIf IsNothing(cmDDoctor.SelectedValue) OrElse cmDDoctor.SelectedValue <= 0 OrElse Trim(cmDDoctor.Text) = "" Then
                BCommon.ShowMsgError(10319)
                cmDDoctor.Focus()
                Return False
            Else
                Return True
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "ValidateData")
            Return False
        End Try
    End Function

    ''Private Function SetData() As CPerson
    ''    Try
    ''        Dim Person As New CPerson
    ''        Dim Name() As String
    ''        Dim intCount As Integer

    ''        With Person
    ''            .Title = cmbTitle.SelectedValue.ToString
    ''            Name = cmDCustomerName.Text.Split(" ")
    ''            For intCount = 0 To Name.Length - 1
    ''                If intCount = 0 Then
    ''                    .First_Name = Name(intCount)
    ''                ElseIf intCount = 1 Then
    ''                    .Middle_Name = Name(intCount)
    ''                ElseIf intCount = 2 Then
    ''                    .Last_Name = Name(intCount)
    ''                End If
    ''            Next
    ''            .First_Name = IIf(.First_Name = Nothing, "", .First_Name)
    ''            .Middle_Name = IIf(.Middle_Name = Nothing, "", .Middle_Name)
    ''            .Last_Name = IIf(.Last_Name = Nothing, "", .Last_Name)
    ''        End With
    ''        Return Person
    ''    Catch ex As Exception
    ''        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetData")
    ''        Return Nothing
    ''    End Try
    ''End Function

    'Private Sub CalculateReturnAmt()
    '    Dim dblPaidAmount As Double = 0
    '    Dim dblGrossAmt As Double = 0
    '    Try

    '        If Me.txtPaidAmt.Text <> "" Then
    '            dblPaidAmount = Convert.ToDouble(Me.txtPaidAmt.Text.ToString())
    '        Else
    '            dblPaidAmount = 0.0
    '            Me.txtPaidAmt.Text = "0.00"
    '        End If

    '        If Me.txtNetAmount.Text <> "" Then
    '            dblGrossAmt = Convert.ToDouble(Me.txtNetAmount.Text.ToString())
    '        Else
    '            dblGrossAmt = 0.0
    '        End If

    '        If dblPaidAmount > dblGrossAmt Then
    '            BCommon.ShowMsgError(10171)
    '            Me.txtPaidAmt.Text = Format(dblGrossAmt, "0.00")
    '            Me.txtBalance.Text = Format((dblGrossAmt - Convert.ToDouble(Me.txtPaidAmt.Text.ToString())), "0.00")
    '        Else
    '            Me.txtBalance.Text = Format((dblGrossAmt - dblPaidAmount), "0.00")
    '        End If

    '    Catch ex As Exception
    '        BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "CalculateReturnAmt")
    '    End Try
    'End Sub
#End Region '"USER DEFINED FUNCITONS"

#Region "PRINT BILL REPORT"

    Public Sub PrintFinalBill()
        Dim Layoutid As Integer

        Dim PWi As Double
        Dim Ps As PaperSize
        Dim dtGetData As New DataTable

        Try

            Layoutid = BCommon.GetPrefValue("SALEBILLLAYOUT")
            If Layoutid <= 0 Then
                BCommon.ShowMsgError(10338)
                Exit Sub
            End If
            dtGetData = DDocument.GetData(Layoutid)
            If dtGetData.Rows.Count > 0 Then
                With PrintDocument1.DefaultPageSettings
                    PHi = (dtGetData.Rows(0).Item("Height") * 100)
                    PWi = (dtGetData.Rows(0).Item("Width") * 100)
                    Ps = New PaperSize("Cust", PWi, PHi)

                    .Margins.Top = (dtGetData.Rows(0).Item("TopM") * 100)
                    .Margins.Bottom = (dtGetData.Rows(0).Item("BottomM") * 100)
                    .Margins.Left = (dtGetData.Rows(0).Item("LeftM") * 100)
                    .Margins.Right = (dtGetData.Rows(0).Item("RightM") * 100)
                    .PaperSize = Ps
                End With
            End If

            headfont = New Font("MS Serif", 12, FontStyle.Bold)
            tableFont = New Font("MS Serif", 8)
            titlefont = New Font("MS Serif", 9)
            tabletitlefont = New Font("MS Serif", 8, FontStyle.Bold)

            X1 = PrintDocument1.DefaultPageSettings.Margins.Left

            With PrintDocument1.DefaultPageSettings
                pageWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
            End With

            X2 = X1 + 120
            X3 = X2 + pageWidth * 0.5

            'COLLECT THE FOOTER LINES 
            Foot1 = BCommon.GetPrefValue("SALEFOOT1")
            Foot2 = BCommon.GetPrefValue("SALEFOOT2")
            Foot3 = BCommon.GetPrefValue("SALEFOOT3")

            'IF U WANT TO PRINT DIRECTLY THEN
            '    PrintDocument1.Print()
            'ELSEIF U WANT PRINT AFTER PRINT PREVIEW THEN U PLS USE THIS CODE

            If ConfigurationManager.AppSettings("Mode").ToString() = "D" Then
                PrintPreviewDialog1.Document = PrintDocument1
                'Divya @ 14/03/2008
                PrintPreviewDialog1.ShowIcon = True
                'Me.PrintPreviewDialog1.Icon = Global.Pharmacy.My.Resources.RxOffice1Icon32x32
                '>>End
                PrintPreviewDialog1.ShowDialog()
            Else
                PrintDocument1.Print()
            End If

        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "PrintFinalBill")
        End Try
    End Sub
    Private Function GetFooterHeight(ByVal e As System.Drawing.Printing.PrintPageEventArgs) As Integer
        Dim TextSize As New System.Drawing.SizeF
        Dim TotFooterHieght As Integer
        TextSize = e.Graphics.MeasureString("Pharmacist", titlefont)
        '3 Footer Line And One Total Amount Line 
        TotFooterHieght = TextSize.Height * 5
        Return TotFooterHieght
    End Function

    Private Sub SetPageHeader(ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim X As Integer
        Dim dtFirm As New DataTable
        Dim TextSize As New System.Drawing.SizeF
        Dim XStart As Integer
        Dim fmtr As New StringFormat(StringFormatFlags.NoClip)
        Dim fmtalign As New StringFormat(fmtr)

        Try
            dtFirm = BCommon.FirmInfo()
            With PrintDocument1.DefaultPageSettings
                X = .PaperSize.Width - .Margins.Left - .Margins.Right
            End With

            If PageNo > 1 Then 'For Next Pages in Same Bill Page No print instead of Date
                TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                XStart = X - (TextSize.Width + 10)
            Else
                'HEADER STATIC
                TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                XStart = X - (TextSize.Width + 10)
            End If
            fmtalign.Alignment = StringAlignment.Far
            If dtFirm.Rows.Count > 0 Then
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont)
                e.Graphics.DrawString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                If PageNo > 1 Then
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("Page No : " & PageNo, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                Else
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("Date:" & Format(Now, "dd/MM/yy"), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                End If

                'Text Size Set to Height of FirmName.
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("FirmName").ToString()), headfont)
                curY = curY + TextSize.Height

                e.Graphics.DrawString(Trim(dtFirm.Rows(0).Item("addDesc1").ToString()) & "," & Trim(dtFirm.Rows(0).Item("Description").ToString()) & "-" & Trim(dtFirm.Rows(0).Item("PinCode").ToString()) & ", Tel: " & Trim(dtFirm.Rows(0).Item("phone1").ToString()), titlefont, Brushes.Black, X1, curY)
                'e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, TextSize.Height))
                TextSize = e.Graphics.MeasureString(Trim(dtFirm.Rows(0).Item("addDesc1").ToString()) & "," & Trim(dtFirm.Rows(0).Item("Description").ToString()) & "-" & Trim(dtFirm.Rows(0).Item("PinCode").ToString()) & ", Tel: " & Trim(dtFirm.Rows(0).Item("phone1").ToString()), titlefont)

                curY = curY + TextSize.Height

            Else  'IF FIRM INFORMATION NOT FOUND
                If PageNo > 1 Then 'Pankaj
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("", headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, TextSize.Height))
                    e.Graphics.DrawString("Page No : " & PageNo, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                Else
                    TextSize = e.Graphics.MeasureString("Date: dd/MM/yy", titlefont)
                    e.Graphics.DrawString("", headfont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, TextSize.Height))
                    e.Graphics.DrawString("Date:" & Format(Now, "dd/MM/yy"), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                End If
                curY = curY + TextSize.Height
                'e.Graphics.DrawString("", titlefont, Brushes.Black, X1, curY)
                ''e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, TextSize.Height))
                'TextSize = e.Graphics.MeasureString("", titlefont)
                'curY = curY + TextSize.Height
            End If

            'HEADER LINE 2
            If PageNo = 1 Then
                If cmDCustomerName.Text <> "" Then
                    If txtAddress.Text <> "" Then
                        TextSize = e.Graphics.MeasureString("Add : " & txtAddress.Text.ToString(), titlefont)
                    Else
                        TextSize = e.Graphics.MeasureString("Add : XXXXXX", titlefont)
                    End If
                    XStart = X - (TextSize.Width + 10)
                    e.Graphics.DrawString("Patient   : " & cmDCustomerName.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                    If txtAddress.Text <> "" Then
                        e.Graphics.DrawString("Add : " & txtAddress.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                    Else
                        e.Graphics.DrawString("Add : ", titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height))
                    End If

                    curY = curY + TextSize.Height
                End If
            End If

            'HEADER LINE 3  
            If cmDDoctor.Text <> "" Then
                TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
                XStart = X - (TextSize.Width + 10)
                If PageNo = 1 Then
                    e.Graphics.DrawString("Doctor : " & cmDDoctor.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                Else
                    e.Graphics.DrawString("", titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
                End If
                'TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
                'XStart = X - (TextSize.Width) + 10
                e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart + X1, curY, TextSize.Width + 10, TextSize.Height), fmtalign)
                TextSize = e.Graphics.MeasureString("Doctor : " & cmDDoctor.Text.ToString(), titlefont)
                curY = curY + TextSize.Height
            End If
            'If cmDDoctor.Text <> "" Then
            '    TextSize = e.Graphics.MeasureString("Bill No:" & txtVoucher.Text, titlefont)
            '    XStart = X - (TextSize.Width)
            '    e.Graphics.DrawRectangle(Pens.Black, X1, curY, XStart, TextSize.Height) '--
            '    e.Graphics.DrawString("Doctor : " & cmDDoctor.Text.ToString(), titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart, TextSize.Height))
            '    e.Graphics.DrawRectangle(Pens.Black, XStart, curY, TextSize.Width, TextSize.Height) '--
            '    e.Graphics.DrawString("Bill No:" & txtVoucher.Text, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width, TextSize.Height), fmtalign)
            '    TextSize = e.Graphics.MeasureString("Doctor : " & cmDDoctor.Text.ToString(), titlefont)
            '    curY = curY + TextSize.Height
            'End If


            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
                'X = .PaperSize.Width - .Margins.Left - .Margins.Right
                wi = X / 20
            End With

            'DESC  +  COMP  +  EXP  + BATCH + QTY  + AMOUNT 
            '  8   +    2   +   1.5   +   3   +   2  +   2
            'Caption of the Print Bill
            '=========================

            e.Graphics.DrawString("Description", tabletitlefont, Brushes.Black, X1, curY)
            e.Graphics.DrawString("Comp", tabletitlefont, Brushes.Black, X1 + (wi * 8), curY)
            e.Graphics.DrawString("Exp", tabletitlefont, Brushes.Black, X1 + (wi * 9.5), curY)
            e.Graphics.DrawString("CLRcode", tabletitlefont, Brushes.Black, X1 + (wi * 11.5), curY)
            e.Graphics.DrawString("Qty", tabletitlefont, Brushes.Black, X1 + (wi * 16), curY)
            e.Graphics.DrawString("Amount", tabletitlefont, Brushes.Black, X1 + (wi * 18), curY)
            TextSize = e.Graphics.MeasureString("Description", tabletitlefont)
            curY = curY + TextSize.Height
            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
            End With
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetPageHeader")
        End Try
    End Sub

    Private Sub SetPageFooter(ByVal e As System.Drawing.Printing.PrintPageEventArgs)
        Dim TextSize As New System.Drawing.SizeF
        Dim FooterRowHieght As Integer
        Dim XStart As Integer
        Dim PWidth As Integer ' Page Width 
        Dim tempstr As String
        Try
            If e.HasMorePages = False Then
                TextSize = e.Graphics.MeasureString("Pharmacist", titlefont)
            Else
                TextSize = e.Graphics.MeasureString("...Cotinued", titlefont)
            End If
            FooterRowHieght = TextSize.Height

            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
                PWidth = .PaperSize.Width - .Margins.Right
            End With

            If e.HasMorePages = False Then
                TextSize = e.Graphics.MeasureString("Net Amt : " & ConfigurationManager.AppSettings("Currency") & " " & Me.txtNetAmount.Text.ToString(), titlefont)
                XStart = PWidth - (TextSize.Width + 10)

                'e.Graphics.DrawString("Total : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, (XStart / XStart) + 1, curY)
                'e.Graphics.DrawString("Total : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, (XStart / 5), curY)
                e.Graphics.DrawString("Total :" & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal.ToString()), titlefont, Brushes.Black, X1, curY)

                If txtDiscount.Text <> "" Then
                    e.Graphics.DrawString("Disc : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(Math.Round(CDbl(txtDiscount.Text), 2).ToString()), titlefont, Brushes.Black, (XStart / 2), curY)
                End If
                e.Graphics.DrawString("Net Amt : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(dobTotal - CDbl(txtDiscount.Text)), titlefont, Brushes.Black, XStart, curY)
                curY = curY + FooterRowHieght

                e.Graphics.DrawString("Paid : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(Math.Round(dobTotal - CDbl(txtDiscount.Text), 2).ToString()), titlefont, Brushes.Black, (XStart / 2), curY)
                'If txtDiscount.Text <> "" Then
                '    'e.Graphics.DrawString("Paid : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(Math.Round(CDbl(txtPaidAmt.Text), 2).ToString()), titlefont, Brushes.Black, (XStart / 2) - 30, curY)

                'End If
                TextSize = e.Graphics.MeasureString("Bal Amt : " & ConfigurationManager.AppSettings("Currency") & " 0.00 ", titlefont)
                XStart = PWidth - (TextSize.Width + 10)

                'e.Graphics.DrawString("Balance Amount : " & ConfigurationManager.AppSettings("Currency") & " " & BCommon.CheckDecimal(txtBalance.Text.ToString()), titlefont, Brushes.Black, XStart - 30, curY)
                e.Graphics.DrawString("Bal Amt : " & ConfigurationManager.AppSettings("Currency") & " 0.00 ", titlefont, Brushes.Black, XStart, curY)
                curY = curY + FooterRowHieght
                dobTotal = 0.0 'ReSet dobTotal to 0 because it is globaly defined.
            End If

            With PrintDocument1.DefaultPageSettings
                e.Graphics.DrawLine(Pens.Black, .Margins.Left, curY, .PaperSize.Width - .Margins.Right, curY)
            End With

            If e.HasMorePages = False Then
                '*********FOOTER SECTION
                'FOOTER LINE 1
                tempstr = "For " & BCommon.GetFirmFullName
                TextSize = e.Graphics.MeasureString(tempstr, titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                e.Graphics.DrawString(Foot1, titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, FooterRowHieght))
                e.Graphics.DrawString(tempstr, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width, FooterRowHieght))
                curY = curY + FooterRowHieght
                'FOOTER LINE 2
                e.Graphics.DrawString(Foot2, titlefont, Brushes.Black, X1, curY)
                curY = curY + FooterRowHieght
                'FOOTER LINE 3
                tempstr = "Pharmacist"
                TextSize = e.Graphics.MeasureString(tempstr, titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                e.Graphics.DrawString(Foot3, titlefont, Brushes.Black, DrawRectangelF(X1, curY, XStart - 10, FooterRowHieght))
                e.Graphics.DrawString(tempstr, titlefont, Brushes.Black, DrawRectangelF(XStart, curY, XStart, FooterRowHieght))
            Else
                TextSize = e.Graphics.MeasureString("...Continued", titlefont)
                XStart = PWidth - (TextSize.Width + 10)
                curY = curY + TextSize.Height
                e.Graphics.DrawString("...Cotinued", titlefont, Brushes.Black, DrawRectangelF(XStart, curY, TextSize.Width, FooterRowHieght))
            End If
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "SetPageFooter")
        End Try
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
        Dim fmtr As New StringFormat(StringFormatFlags.NoClip)
        Dim fmtalgin As New StringFormat(fmtr)

        Dim TextSize As New System.Drawing.SizeF
        ''Dim QtySize As New System.Drawing.SizeF
        Y = PrintDocument1.DefaultPageSettings.Margins.Top + 10
        curY = PrintDocument1.DefaultPageSettings.Margins.Top + 10
        Dim count As Integer = 0
        Dim intCount As Integer = 1
        Dim curRowHeight As Integer
        Dim FootStart As Integer
        ''Dim Xstart As New System.Drawing.SizeF
        ''Dim textWidth As New System.Drawing.SizeF


        Try
            Call SetPageHeader(e) 'Setting the Header
            FootStart = PHi - GetFooterHeight(e) - PrintDocument1.DefaultPageSettings.Margins.Bottom
            For intCount = intPrintNext To fgItems.Rows.Count - 1
                If IsNothing(fgItems.Item(intCount, "ITEMNAME")) = False Then
                    TextSize = e.Graphics.MeasureString(fgItems.Item(intCount, "ITEMNAME").ToString(), tableFont)
                    curRowHeight = TextSize.Height
                    'DESC  +  COMP  +  EXP  + BATCH + QTY  + AMOUNT 
                    '  8   +    2   +   1.5   +   3   +   2  +   2

                    If FootStart > curY + curRowHeight Then
                        e.Graphics.DrawString(fgItems.Item(intCount, "ITEMNAME").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1, curY, (wi * 8) - 2, curRowHeight), fmt)
                        e.Graphics.DrawString(fgItems.Item(intCount, "COMPANY").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 8), curY, (wi * 1.5) - 2, curRowHeight), fmt)
                        e.Graphics.DrawString(Format(CDate(fgItems.Item(intCount, "EXP").ToString()), "MM/yy"), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 9.5), curY, (wi * 2) - 2, curRowHeight), fmt)
                        e.Graphics.DrawString(Trim(fgItems.Item(intCount, "CLRcode")), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 11.5), curY, (wi * 3) - 2, curRowHeight), fmt)
                        fmtalgin.Alignment = StringAlignment.Far
                        e.Graphics.DrawString(fgItems.Item(intCount, "QTY").ToString(), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 14.5), curY, (wi * 2) - 2, curRowHeight), fmtalgin)
                        e.Graphics.DrawString(BCommon.CheckDecimal(fgItems.Item(intCount, "AMOUNT").ToString()), tableFont, Brushes.Black, DrawRectangelF(X1 + (wi * 16.5), curY, (wi * 3) - 5, curRowHeight), fmtalgin)

                        If IsNothing(fgItems.Item(intCount, "AMOUNT")) = False Then
                            dobTotal = dobTotal + Convert.ToDouble(fgItems.Item(intCount, "AMOUNT").ToString())
                        End If
                        count = count + 1
                        curY = curY + curRowHeight
                        e.HasMorePages = False
                        intPrintNext = 1
                    Else
                        e.HasMorePages = True
                        intPrintNext = intCount
                        curY = FootStart
                        Call SetPageFooter(e)   'Setting the Footer When Record goes to Next Page
                        PageNo = PageNo + 1
                        Exit For
                    End If
                Else
                    curY = FootStart
                    Call SetPageFooter(e)      'Setting the Footer When Record Available in One Page
                    PageNo = 1
                    Exit For
                End If
            Next
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "PrintDocument1_PrintPage")
        End Try

    End Sub

    Private Function DrawRectangelF(ByVal x As Integer, ByVal y As Integer, ByVal width As Integer, ByVal height As Integer) As RectangleF
        Try
            Dim drawRect As New RectangleF(x, y, width, height)
            Return drawRect
        Catch ex As Exception
            BCommon.ErrorHandler(ex.Message, Me.ProductName, Me.Name, "DrawRectangelF")
        End Try
    End Function
#End Region '"PRINT BILL REPORT"      

End Class
